class Order < ActiveRecord::Base
  
  validates :order_no, :uniqueness => true
  validates :sale_price,
    :order_price, 
    :numericality => {
      :greater_than_or_equal_to => 0
    }, 
    :on => :update    
  
  belongs_to :buyer
  belongs_to :dept
  belongs_to :saler, :class_name => "Employee", :foreign_key => "saler_id"
  belongs_to :creator, :class_name => "Employee", :foreign_key => "creator_id"
  has_many :order_items
  has_many :feeds, :dependent => :destroy
  
  before_create do |order|
    order.init_order_no
    order.creator ||= Employee.current
    order.dept ||= Dept::Storefront.first
  end
    
  scope :being_edited, where(:status => 'being_edited')
  scope :effected, where(:status => 'effected')
  scope :blanked_out, where(:status => 'blanked_out')
  
  def init_order_no
    self.order_no ||= "OD#{DateTime.now.to_formatted_s(:number)}"
  end  
  
  def status
    ActiveSupport::StringInquirer.new(self[:status])
  end
  
  def edited!
    update_attribute :status, 'being_edited'
  end
  
  def blanked_out!
    self.status = 'blanked_out'
    self.blanked_out_at = DateTime.now
    save(:validate => false)
  end
  
  # 设置状态为生效
  def effected!
    self.status = 'effected'
    self.effected_at = DateTime.now
    save(:validate => false)
  end
  
  # 可安装数
  def can_be_installed_count
    order_items.each_with_object([]) do |item,counts|
      if(item.is_a?(OrderItem::FactoryOrderMade))
        counts << item.can_be_installed_count
      elsif(item.is_a?(OrderItem::SpotsOrdered))
        item.furniture_logistic_stat_order_items.each_with_object(counts) do |stat_order_item,counts|
          counts << stat_order_item.can_be_installed_count
        end
      else
        raise "不支持的类型:#{item}}"
      end
    end.sum
  end

end
